package com.tempjob.common.businesss.mongo.service.impl;

import com.alibaba.fastjson.JSON;
import com.anwen.mongo.service.impl.ServiceImpl;
import com.tempjob.common.businesss.mongo.entity.SysSmsLog;
import com.tempjob.common.businesss.mongo.service.SysSmsLogService;
import com.tempjob.common.businesss.service.AliSmsService;
import com.tempjob.common.enums.SmsTypeEnums;
import com.tempjob.common.exception.BusinessException;
import com.tempjob.common.utils.CommFunction;
import com.tempjob.common.utils.DateUtilsEx;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hui
 * @description 针对表【sys_user(系统用户)】的数据库操作Service实现
 * @createDate 2024-02-18 18:57:52
 */
@Slf4j
@Service
public class SysSmsLogServiceImpl extends ServiceImpl<SysSmsLog> implements SysSmsLogService {


    @Autowired
    private AliSmsService aliSmsService;

    @Override
    public void userRegistNotice(String mobile) {
        long smsLogCount = this.lambdaQuery().eq(SysSmsLog::getMobile, mobile).eq(SysSmsLog::getMobile, mobile).gte(SysSmsLog::getCreateTime, DateUtilsEx.getDayStart(new Date())).count();
        if (smsLogCount > 10) {
            throw new BusinessException("短信验证次数超过限制!");
        }
        SysSmsLog smsLog = new SysSmsLog();
        smsLog.setMobile(mobile);
        smsLog.setCreateTime(new Date());
        smsLog.setStatus(0);
        smsLog.setSmsType(1);
        Map<String, String> params = new HashMap<>();
        String code = CommFunction.getRandomCode(6);
        smsLog.setContent(code);
        params.put("code", code);
        String send = aliSmsService.sendNoticeSms(mobile, SmsTypeEnums.REGIST_NOTICE, JSON.toJSONString(params));
        if (StringUtils.isNotBlank(send)) {
            smsLog.setSmsRequestId(send);
            smsLog.setStatus(1);
            smsLog.setLimitTime(new Date(System.currentTimeMillis() + 10 * 60 * 1000));
        }
        this.save(smsLog);
    }

    @Override
    public Boolean vaildateSms(String mobile, Integer smsType, String code) {
        SysSmsLog smsLog = this.lambdaQuery().eq(SysSmsLog::getMobile, mobile).eq(SysSmsLog::getSmsType, smsType).eq(SysSmsLog::getContent, code).gte(SysSmsLog::getLimitTime, DateUtilsEx.getDayEnd(new Date())).one();
        if (smsLog == null) {
            return false;
        }
        smsLog.setStatus(2);
        smsLog.setOperTime(new Date());
        return this.updateById(smsLog);
    }

}




